package com.hzya.frame.web.aop;

import com.hzya.frame.utils.core.annotation.PrimaryName;
import com.hzya.frame.utils.core.dao.IBaseDao;
import com.hzya.frame.utils.core.entity.BaseEntity;
import com.hzya.frame.utils.help.BeanHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import java.lang.reflect.Field;

@Aspect
public class RepeatedCheck {

	@Pointcut("execution(* com.hzya..IBaseDao+.save*(..)) || execution(* com.hzya..IBaseDao+.update*(..))")
	public void savePoint() {

	};

	private String checkMethodName;

	@Around("savePoint()")
	public Object runRound(ProceedingJoinPoint joinPoint) throws Throwable {
		Object target = joinPoint.getTarget();
		Object[] params = joinPoint.getArgs();
		Object param = null;
		Object result = null;
		boolean runFlag=true;
		if (target instanceof IBaseDao) {
			if (null != params && 0 < params.length) {
				for (int i = 0; i < params.length; i++) {
					param = params[i];
					if (param instanceof BaseEntity) {
						boolean flag = (Boolean) BeanHelper.invoke(target, checkMethodName, new Object[] { param });
						if (flag) {
							Class targetClass = param.getClass();
							Field[] fields = targetClass.getDeclaredFields();
							StringBuffer stringBuffer = null;
							String resultStr = null;
							String tempStr = null;
							for (int j = 0; j < fields.length; j++) {
								Field field = (Field) fields[j];
								if (field.isAnnotationPresent(PrimaryName.class)) {
									PrimaryName primaryName = field.getAnnotation(PrimaryName.class);
									if (primaryName.msg() != null && !"".equals(primaryName.msg())) {
										if (stringBuffer == null)
											stringBuffer = new StringBuffer();
										stringBuffer.append(primaryName.msg());
									}
								}
							}
							resultStr = (stringBuffer == null ? "数据出现重复,请重新输入" : stringBuffer.toString());
							throw new RuntimeException(resultStr);
						} else {
							result = joinPoint.proceed();
							runFlag=false;
						}
					}
				}
				if(null==result && runFlag)
					result = joinPoint.proceed();

			} else {
				result = joinPoint.proceed();
			}
		} else {
			result = joinPoint.proceed();
		}
		return result;
	}

	public String getCheckMethodName() {
		return checkMethodName;
	}

	public void setCheckMethodName(String checkMethodName) {
		this.checkMethodName = checkMethodName;
	}

}
